package com.codefish.codefishseckill.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * redis service类
 *
 * @author codefish
 * @version 1.0
 * @date 2022/07/21 上午 10:42
 */
@Service
@Slf4j
public class RedisService {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;
    @Autowired
    ScheduledExecutorService scheduledExecutorService;


    /**
     * 从redis中删除
     *
     * @param key key
     */
    public void deleteKey(String key) {
        redisTemplate.delete(key);
        log.debug("已将key值为{}的数据从Redis删除", key);
    }

    /**
     * 延时从redis中删除，默认3s
     *
     * @param key 要删除的key
     */
    public void deleteKeyDelay(String key) {
        scheduledExecutorService.schedule(() -> {
            redisTemplate.delete(key);
            log.debug("已将key值为{}的数据从Redis删除", key);
        }, 3, TimeUnit.SECONDS);
    }

    /**
     * 延时从redis中删除
     *
     * @param key      key
     * @param delay    时间
     * @param timeUnit 单位
     */
    public void deleteKeyDelay(String key, long delay, TimeUnit timeUnit) {
        scheduledExecutorService.schedule(() -> {
            redisTemplate.delete(key);
            log.debug("已将key值为{}的数据从Redis删除", key);
        }, delay, timeUnit);
    }

}
